<?php


namespace app\admin\validate;


use think\Validate;
use app\admin\model\Admin as AdminModel;

class Admin extends Validate
{

    protected $rule = [
        'username' => 'require|length:3,16|alphaDash',
        'password'  =>  'require|length:6,16',
        'email'   => 'email',
        'state' => 'require|in:1,0',
        'verify'=>'require|captcha'
    ];



    protected $field = [
        'username'      => '管理员名称',
        'password'      => '密码',
        'email'         => '邮箱',
        'state'        => '审核状态',
        'role'          => '管理员角色',
        'verify'       =>'验证码'
    ];

    protected $message = [

    ];

    protected $scene = [
        'add' => ['username','password', 'email', 'state'],
        'edit' => ['username','password','email', 'state'],
        'no_change' => ['username','email', 'state']
    ];

    // 登录 验证场景定义
    public function sceneLogin()
    {
        return $this->only(['username','password','verify'])
            ->append('username', 'token')
            ->append('password', 'checkName');
    }

    // 自定义验证规则验证用户
    protected function checkName($value, $rule, $data=[])
    {
        $model = AdminModel::where('username|email',$data['username'])->find();
        if (!$model){
            return '账号不存在';
        }

        if ($model->state==0){
            return '账号已冻结请联系管理员';
        }

        if (md5($value.$model->token)!=$model->password){
            return '账户密码错误';
        }
        return true;
    }
}
